package cn.e3mall.search.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.e3mall.common.pojo.SearchItem;
import cn.e3mall.common.pojo.SearchResult;

/**
 * 商品搜索dao
 * @author zhouzhixiang
 *
 */
@Repository
public class SearchDao {

	@Autowired
	private SolrServer solrServer;
	/*
	 * 根据查询条件查询索引
	 */
	
	public SearchResult searchResult(SolrQuery query) throws SolrServerException{
		//根据query查询索引库
		QueryResponse queryResponse=solrServer.query(query);
		//取查询结
		SolrDocumentList documentList = queryResponse.getResults();
		long numFound=documentList.getNumFound();
		SearchResult searchResult= new SearchResult();
		searchResult.setRecordCount(numFound);
		List<SearchItem> list = new ArrayList<SearchItem>();
		Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
		for (SolrDocument doc : documentList) {
			SearchItem item = new SearchItem();
			item.setId(doc.get("id").toString());
			item.setCategory_name(doc.get("item_category_name").toString());
			item.setImage(doc.get("item_image").toString());
			item.setPrice((long)doc.get("item_price"));
			item.setSell_point(doc.get("item_sell_point").toString());
			//取高亮
			List<String> list2 = highlighting.get(doc.get("id")).get("item_title");
			String title="";
			if (list!=null &&list.size()>0) {
				title=list2.get(0);
			}else{
				title=doc.get("item_title").toString();
			}
			item.setTitle(title);
			list.add(item);
		}
		searchResult.setItemList(list);
		//取查询结果总记录数
		//取查询商品列表高亮
		return searchResult;
	}


}
